package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        // 1. 查询所有分类
        List<CategoryEntity> entityList = baseMapper.selectList(null);

        // 2. 组装父子结构
        List<CategoryEntity> list = entityList.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map(item -> {
            item.setChildren(getChildren(item, entityList));
            return item;
        }).sorted((item1, item2) -> {
            return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
        }).collect(Collectors.toList());

        return list;
    }

    private List<CategoryEntity> getChildren(CategoryEntity menu, List<CategoryEntity> entityList) {
        List<CategoryEntity> list = entityList.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(menu.getCatId())).map(item -> {
            item.setChildren(getChildren(item, entityList));
            return item;
        }).sorted((item1, item2) -> {
            return (item1.getSort() == null ? 0 : item1.getSort()) - (item2.getSort() == null ? 0 : item2.getSort());
        }).collect(Collectors.toList());

        return list;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前删除的菜单，是否被别的地方引用
        // 逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, path);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

//    @CacheEvict(value = {"category"}, key = "'getLevel1Categorys'")   // 删除两个需要，这样写就不对了


    // 这是一种写法
//    @Caching(evict = {
//            @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category", key = "'getCatalogJson6'")
//    })
    // 这是一种写法
    @CacheEvict(value = "category", allEntries = true)
    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Cacheable(value = "category", key = "#root.method.name") // 如果key是普通字符串，一定加上单引号
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys");
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    /**
     * 二三级分类数据
     * @return
     */
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        // 查询所有的一级分类
        List<CategoryEntity> level1Categorys = getLevel1Categorys();
        // 封装数据
        Map<String, List<Catalog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 查找每一个一级分类下的二级分类
            List<CategoryEntity> level2Categorys = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catalog2Vo> catalog2VoList = null;
            if (level2Categorys != null) {
                catalog2VoList = level2Categorys.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 查询三级分类
                    List<CategoryEntity> level3Categorys = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    if (level3Categorys != null){
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = level3Categorys.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2VoList;
        }));

        return map;
    }

    /**
     * 查一次库，对第一次获取二三级分类的优化
     * @return
     */
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson2() {
        synchronized (this){
            Map<String, List<Catalog2Vo>> map = getDataFromDb();
            return map;
        }
    }

    /**
     * 优化，加入缓存逻辑
     * @return
     */
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson3() {
        // 1. 加入缓存逻辑，缓存中存储的是json字符串
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isEmpty(catelogJson)){
            // 2. 缓存中没有，查数据库。
//            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJson2(); // 本地锁
//            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJson4();    // 分布式redis锁
            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJson5();    // 分布式redisson锁
            return catalogJsonFromDb;
        }
        System.out.println("直接命中缓存...");
        // 缓存中有，将json转为对象放回
        Map<String, List<Catalog2Vo>> map = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return map;
    }

    /**
     * 使用springcache的测试
     * @return
     */
    @Cacheable(value = "category", key = "#root.method.name")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson6() {
        System.out.println("查询了数据库...");
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 查询所有的一级分类
        List<CategoryEntity> level1Categorys = getByParentCid(selectList, 0l);
        // 封装数据
        Map<String, List<Catalog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 查找每一个一级分类下的二级分类
            List<CategoryEntity> level2Categorys = getByParentCid(selectList, v.getCatId());
            List<Catalog2Vo> catalog2VoList = null;
            if (level2Categorys != null) {
                catalog2VoList = level2Categorys.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 查询三级分类
                    List<CategoryEntity> level3Categorys = getByParentCid(selectList, l2.getCatId());
                    if (level3Categorys != null){
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = level3Categorys.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2VoList;
        }));
        return map;
    }

    /**
     * 分布式锁 redisson 实现
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogJson5() {
        // 1. 注意锁的名字 也就是锁的粒度， 越细越快
        // 锁的粒度指的是具体缓存的某个数据， 比如11-商品/12-商品： product-11-lock、 product-12-lock ， 不建议使用product-lock一个锁
        RLock rLock = redissonClient.getLock("CatalogJson-lock");
        rLock.lock();
        Map<String, List<Catalog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        }finally {
            rLock.unlock();
        }
        return dataFromDb;
    }


    /**
     * 复制的 getCatalogJson2
     *  getCatalogJson2 是 本地local锁
     *  本方法getCatalogJson4是redis锁
     * @return
     */
    private Map<String, List<Catalog2Vo>> getCatalogJson4() {

        // 占分布式锁， 去redis 去占坑 设置过期时间，方式锁释放不了造成死锁
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if (lock){
            // 加锁成功 执行业务
            Map<String, List<Catalog2Vo>> dataFromDb = getDataFromDb();
            // 删除锁
            String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
            redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            return dataFromDb;
        }else {
            // 加锁失败， 重试（或休眠100ms重试）
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJson4();
        }

    }

    /**
     * getCatalog2、getCatalog4查询数据库代码抽取
     * @return
     */
    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        // 进同步之后还要先查一下缓存
        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isNotBlank(catelogJson)){
            // 缓存中有，将json转为对象放回
            System.out.println("第二次查询命中了缓存...");
            Map<String, List<Catalog2Vo>> map = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
            return map;
        }

        System.out.println("查询了数据库...");

        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 查询所有的一级分类
        List<CategoryEntity> level1Categorys = getByParentCid(selectList, 0l);
        // 封装数据
        Map<String, List<Catalog2Vo>> map = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 查找每一个一级分类下的二级分类
            List<CategoryEntity> level2Categorys = getByParentCid(selectList, v.getCatId());
            List<Catalog2Vo> catalog2VoList = null;
            if (level2Categorys != null) {
                catalog2VoList = level2Categorys.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 查询三级分类
                    List<CategoryEntity> level3Categorys = getByParentCid(selectList, l2.getCatId());
                    if (level3Categorys != null){
                        List<Catalog2Vo.Catalog3Vo> catalog3Vos = level3Categorys.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2VoList;
        }));
        // 3. 将对象序列化后，放入到缓存
        redisTemplate.opsForValue().set("catelogJson", JSON.toJSONString(map), 1, TimeUnit.DAYS);
        return map;
    }

    private List<CategoryEntity> getByParentCid(List<CategoryEntity> selectList, long parent_cid) {
        List<CategoryEntity> list = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return list;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> path) {
        // 手机当前节点ID
        path.add(catelogId);
        CategoryEntity category = this.getById(catelogId);
        if (category.getParentCid() != 0){
            findParentPath(category.getParentCid(), path);
        }
        return path;
    }


}